package com.itheima.health.service.impl;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @Author: liangWeiQUQ
 * @Description: 订单预约
 * @DateTime: 2021/3/5 14:56
 **/
@DubboService
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
       * @Author: 传闻中的梁大侠
       * @Date: 15:10 2021/3/5
       * @Parms [order]
       * @ReturnType: com.itheima.health.pojo.Order
       * @Description: 点击提交按钮后，添加预约订单的信息
     */

    @Transactional
    @Override
    public Order add(Order order) {
        //1.先查询当天是否可以预约，有没有预约的信息
        OrderSetting orderSetting = orderSettingDao.selectByDate(order.getOrderDate());
        if (orderSetting == null) {
            throw new BusinessException("当天不可预约！");
        }
        //2.查询可预约的人数与已经预约的人数的关系----> 可预约人数<=已预约人数
        if (orderSetting.getNumber() < orderSetting.getReservations()) {
            throw new BusinessException("当天预约人数已满，请选择其他日期！");
        }
        //3.查询该用户在当天是否已经预约过该套餐体检信息
        Order order1 = new Order();
        order1.setMemberId(order.getMemberId());
        order1.setOrderDate(order.getOrderDate());
        order1.setSetmealId(order.getSetmealId());
        int count = orderDao.selectCount(order1);
        if (count > 0) {
            throw new BusinessException("当天已经预约过该体检套餐，省点钱吧！");
        }
        //4.通过后新增套餐信息
        orderDao.insertSelective(order);
        //5.维护t_ordersetting表，是预约的人数+1
        orderSetting.setReservations(orderSetting.getReservations()+1);
        //更新表的数据
        orderSettingDao.updateByPrimaryKeySelective(orderSetting);
        return order;
    }
    /**
     * @Author: 传闻中的梁大侠
     * @Date: 16:14 2021/3/5
     * @Parms [id]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 根据id查询预约订单的信息
     */
    @Override
    public Map<String, Object> findById(Integer id) {
        return orderDao.findById(id);
    }

}
